

import os
import shutil
import random

random.seed(0)

def get123(file_path,xml_path, new_file_path):
    # 定义源文件夹路径和目标文件夹路径------获取只进行标注之后的图片
    folder_path1 = file_path
    folder_path2 = xml_path
    new_folder_path = new_file_path

    # 创建新的目标文件夹
    if not os.path.exists(new_folder_path):
        os.makedirs(new_folder_path)

    # 获取两个文件夹下的所有文件名（不包含路径和后缀）
    files_in_folder1 = set(
        os.path.splitext(os.path.basename(file))[0] for root, dirs, files in os.walk(folder_path1) for file in files)
    files_in_folder2 = set(
        os.path.splitext(os.path.basename(file))[0] for root, dirs, files in os.walk(folder_path2) for file in files)

    # 计算交集（保留同时存在于两个文件夹中的文件名）
    file_names_intersection = files_in_folder1.intersection(files_in_folder2)

    # 遍历交集中的文件名，查找并复制对应的文件至新文件夹
    for base_name in file_names_intersection:
        # 假设图片文件在folder_path1中，XML文件在folder_path2中
        if os.path.exists(os.path.join(folder_path1, base_name + '.jpg')):
            img_source_file = os.path.join(folder_path1, base_name + '.jpg')
            img_destination_file = os.path.join(new_folder_path, base_name + '.jpg')
            shutil.copy2(img_source_file, img_destination_file)

        if os.path.exists(os.path.join(folder_path2, base_name + '.xml')):
            xml_source_file = os.path.join(folder_path2, base_name + '.xml')
            xml_destination_file = os.path.join(new_folder_path, base_name + '.xml')
            shutil.copy2(xml_source_file, xml_destination_file)

    print("已将交集中的文件复制到新文件夹: ", new_folder_path)

def split_data(file_path,xml_path, new_file_path, train_rate, val_rate, test_rate):
    each_class_image = []
    each_class_label = []
    for image in os.listdir(file_path):
        each_class_image.append(image)
    for label in os.listdir(xml_path):
        each_class_label.append(label)
    data=list(zip(each_class_image,each_class_label))
    total = len(each_class_image)
    random.shuffle(data)
    each_class_image,each_class_label=zip(*data)
    train_images = each_class_image[0:int(train_rate * total)]
    val_images = each_class_image[int(train_rate * total):int((train_rate + val_rate) * total)]
    test_images = each_class_image[int((train_rate + val_rate) * total):]
    train_labels = each_class_label[0:int(train_rate * total)]
    val_labels = each_class_label[int(train_rate * total):int((train_rate + val_rate) * total)]
    test_labels = each_class_label[int((train_rate + val_rate) * total):]

    for image in train_images:
        print(image)
        old_path = file_path + '/' + image
        new_path1 = new_file_path + '/' + 'train' + '/' + 'images'
        if not os.path.exists(new_path1):
            os.makedirs(new_path1)
        new_path = new_path1 + '/' + image
        shutil.copy(old_path, new_path)

    for label in train_labels:
        print(label)
        old_path = xml_path + '/' + label
        new_path1 = new_file_path + '/' + 'train' + '/' + 'labels'
        if not os.path.exists(new_path1):
            os.makedirs(new_path1)
        new_path = new_path1 + '/' + label
        shutil.copy(old_path, new_path)

    for image in val_images:
        old_path = file_path + '/' + image
        new_path1 = new_file_path + '/' + 'val' + '/' + 'images'
        if not os.path.exists(new_path1):
            os.makedirs(new_path1)
        new_path = new_path1 + '/' + image
        shutil.copy(old_path, new_path)

    for label in val_labels:
        old_path = xml_path + '/' + label
        new_path1 = new_file_path + '/' + 'val' + '/' + 'labels'
        if not os.path.exists(new_path1):
            os.makedirs(new_path1)
        new_path = new_path1 + '/' + label
        shutil.copy(old_path, new_path)

    for image in test_images:
        old_path = file_path + '/' + image
        new_path1 = new_file_path + '/' + 'test' + '/' + 'images'
        if not os.path.exists(new_path1):
            os.makedirs(new_path1)
        new_path = new_path1 + '/' + image
        shutil.copy(old_path, new_path)

    for label in test_labels:
        old_path = xml_path + '/' + label
        new_path1 = new_file_path + '/' + 'test' + '/' + 'labels'
        if not os.path.exists(new_path1):
            os.makedirs(new_path1)
        new_path = new_path1 + '/' + label
        shutil.copy(old_path, new_path)

def transfer_txtdata(file_path,target_char1, replacement_char1):
    # 定义文件夹路径和要替换的目标字符及替换为的新字符
    folder_path = r"D:\pythonProject\weed_detaction\datasets\corn weed datasets11\sedge\label"  # 替换为你的目标文件夹路径
    target_char = target_char1  # 要被替换的字符
    replacement_char = replacement_char1  # 替换为目标字符

    # 遍历文件夹中的所有.txt文件
    for filename in os.listdir(folder_path):
        if filename.endswith(".txt"):  # 只处理txt文件
            filepath = os.path.join(folder_path, filename)

            # 打开并读取文件内容
            with open(filepath, 'r') as f:
                lines = f.readlines()

            # 替换每行开头的指定字符
            new_lines = [line.replace(target_char, replacement_char, 1) if line.startswith(target_char) else line for
                         line in lines]

            # 写回文件，替换后的内容
            with open(filepath, 'w') as f:
                f.writelines(new_lines)

    # 上述代码会检查每行是否以 `target_char` 开头，如果是，则将开头的那个字符替换为 `replacement_char`。

    # 注意：
    #   - 如果你想要替换任意字符而不是特定字符，请在 replace 函数中调整 target_char。
    #   - 如果要替换的是多个字符（比如空格），或者是一个模式而非单个字符，可能需要使用不同的字符串处理方法。
    #   - 请确保你有足够的权限访问和修改这些文件。


def get_diff(file_path, xml_path):
    # 定义源文件夹路径
    folder_path1 = file_path
    folder_path2 = xml_path

    # 获取两个文件夹下的所有文件名（不包含路径，仅包含基础文件名）
    files_in_folder1 = set(
        os.path.splitext(os.path.basename(file))[0] for root, dirs, files in os.walk(folder_path1) for file in files)
    files_in_folder2 = set(
        os.path.splitext(os.path.basename(file))[0] for root, dirs, files in os.walk(folder_path2) for file in files)

    # 计算差集（此时仅基于文件名，不考虑后缀）
    files_only_in_folder1 = files_in_folder1.difference(files_in_folder2)
    files_only_in_folder2 = files_in_folder2.difference(files_in_folder1)

    # 输出差集中的文件名
    print("仅在文件夹1中存在的文件（忽略后缀）：", files_only_in_folder1)
    print("仅在文件夹2中存在的文件（忽略后缀）：", files_only_in_folder2)





if __name__ == '__main__':

    # file_path = r"D:\pythonProject\Data-enhancement-main\Data-enhancement-main\Data-enhancement\DataAugForObjectDetection\data\imagesAll_force1"
    # xml_path = r'D:\pythonProject\Data-enhancement-main\Data-enhancement-main\Data-enhancement\DataAugForObjectDetection\data\labelAll_force1'
    # new_file_path = r"D:\pythonProject\Data-enhancement-main\Data-enhancement-main\Data-enhancement\DataAugForObjectDetection\data\imagesAll_force2"
    # # 1、处理源image文件，得到只标注的图片
    # get123(file_path,xml_path, new_file_path)

    # file_path = r"D:\pythonProject\Data-enhancement-main\Data-enhancement-main\Data-enhancement\DataAugForObjectDetection\data\weed_img_s"
    # xml_path = r'D:\pythonProject\Data-enhancement-main\Data-enhancement-main\Data-enhancement\DataAugForObjectDetection\data\weed_xml_s'
    # # 2、取差集
    # get_diff(file_path,xml_path)

    file_path = r"D:\pythonProject\Data-enhancement-main\Data-enhancement-main\Data-enhancement\DataAugForObjectDetection\data\imagesAll_cut0.8"
    xml_path = r'D:\pythonProject\Data-enhancement-main\Data-enhancement-main\Data-enhancement\DataAugForObjectDetection\data\labelAll_cut0.8'
    new_file_path = r"D:\pythonProject\Data-enhancement-main\Data-enhancement-main\Data-enhancement\DataAugForObjectDetection\data\weed_cut0.8"
    # 3、分配数据（分配之前把xml转换为txt  在分配）
    split_data(file_path,xml_path, new_file_path, train_rate=0.7, val_rate=0.1, test_rate=0.2)


